package com.ty.service;

import com.ty.entity.Danmu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DanmuService {
    @Autowired
    private MongoTemplate mongoTemplate;
    public void insert(Danmu danmu)
    {
        mongoTemplate.insert(danmu);
    }
    public List<Danmu> select(int veoidId, int time)
    {
        Criteria criteria = Criteria.where("videoId").is(veoidId)
                .and("time").gte(time-2).lt(time+2);
        Query query = new Query(criteria).with(Sort.by("createTime").ascending());
        List<Danmu> danmus = mongoTemplate.find(query, Danmu.class);
        return danmus;
    }

    public List<Danmu> select5(int veoidId)
    {
        Criteria criteria1 = Criteria.where("videoId")
                .is(veoidId);
        Criteria criteria2 = Criteria.where("createTime")
                .gte(LocalDateTime.now().minusSeconds(60*60));
        Criteria criteria = new Criteria();
        criteria.andOperator(
                criteria1,
                criteria2
        );
        Query query = new Query(criteria).with(Sort.by("createTime").descending());
        List<Danmu> danmus = mongoTemplate.find(query, Danmu.class);
        return danmus;
    }
}
